/**
  * @description: 数据中台-权限管理-首页图片管理
  * @author: hj
  * @update: hj(2020-01-14)
  */
import React from 'react';
import Container from '@icedesign/container';
import styles from './index.module.scss';
import event from '@/request'
import {Button, Card, Dialog, Input, MenuButton, Message, Table, Upload} from "@alifd/next";
import ZgDialog from '@/components/ZgDialog';
import $http from '@/service/Services';

const {Item} = MenuButton;


const commonProps = {
    style: {width: 450},
    title: '提示信息',
    subTitle: '上传数据提示'
};

/**
 * list
 */
class PagesList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            subjectId: "",
            current: 0,
            mockData: [],
            selectedList: [],
            uploadVisible: false,
            condition: "",
            errorMsg: [],
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        };
        // 当前页数
        this.pageNum = 1;
        // 分页每页显示数据条数
        this.pageSize = 10;
        // 数据总条数
        this.totalNum = 0;
        this.$http = $http;
        this.handleClick = this.handleClick.bind(this);
        this.onPageChange = this.onPageChange.bind(this);
        this.getAllPageImages = this.getAllPageImages.bind(this);
    }

    /**
     * 在渲染前调用,在客户端也在服务端
     */
    componentWillMount = () => {
        const params = new URLSearchParams(this.props.location.search);
        const id = params.get("id");
        this.setState({
            subjectId: id
        }, () => {
            this.getAllPageImages();
        });
    };


    /**
     * 条件
     * @param e
     * @param value
     */
    searchCondition = (value, e) => {
        this.setState({
            condition: value,
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        });
        this.pageNum = 1;
    };
    /**
     * 改变页面
     * @param currentPage
     */
    onPageChange = (currentPage) => {
        this.state = {
            current: currentPage,
            mockData: this.props.mockData,
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        };
        this.getAllPageImages();
    };
    /**
     * 修改分页数据
     * @param currentPage
     */
    onChangePage = (currentPage) => {
        this.setState({
            loading: true,
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        });
        setTimeout(() => {
            this.getAllPageImages(currentPage);
            this.setState({
                loading: false,
                config: {
                    data: null,
                    visible: false,
                    title: "",
                    content: ""
                }
            });
        }, 0);
    };

    /**
     * 获取数据
     */
    getAllPageImages = () => {
        const _this = this;
        let url = event.event.url + '/v1/loginPageImages/getAllPageImages/-1?name=' + this.state.condition;
        this.$http.get(url)
            .then(function (response) {
                const {data} = response;
                data.data.forEach((o, i) => {
                    o.number = i + 1;
                });
                _this.setState({
                    mockData: data.data,
                    config: {
                        data: null,
                        visible: false,
                        title: "",
                        content: ""
                    }
                });
            })
            .catch(function (error) {
                Message.error(error.message);
            })

    };


    /**
     * 批量操作
     * @param text
     */
    handleClick = () => {
        const {selectedList} = this.state;
        if (selectedList.length == 0) {
            Message.error("请选择需要删除的数据.");
            return null;
        }
        this.setState({
            visible: true
        });
    };

    /**
     *
     * @param args
     */
    onChange = (...args) => {
        this.setState({
            selectedList: args
        });
    };

    /**
     * 批量删除
     * @param ids
     */
    handleSelect = (ids) => {
        const _this = this;
        this.$http.post(event.event.url + '/v1/loginPageImages/deleteImages', {ids: ids})
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    Message.success("操作成功.");
                    _this.getMetadataItemList();
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };

    /**
     * 确定提示弹框
     */
    onOkDialog = () => {
        this.setState({
            visible: false
        });
        const {selectedList} = this.state;
        this.handleSelect(selectedList[1].map(o => {
            return o.id;
        }));
    };
    /**
     * 取消提示弹框
     */
    onCloseDialog = reason => {
        this.setState({
            visible: false
        });
    };

    /**
     * 删除
     */
    okCall = (data) => {
        this.setState({
            config: {
                visible: false
            }
        });
        const _this = this;
        this.$http.post(event.event.url + '/v1/loginPageImages/deleteImages', {ids: [data.id]})
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    Message.success("操作成功.");
                    _this.getAllPageImages();
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };

    /**
     * 删除
     */
    deletePageImages = (row) => {
        this.setState({
                config: {
                    data: row,
                    visible: true,
                    title: "提示消息",
                    content: "删除后不能恢复，确认要删除？"
                }
            }
        )
    };

    // ----------------------- 导入 -----------------------------------------
    /**
     * 取消提示弹框
     */
    onImportCloseDialog = reason => {
        this.setState({
            uploadVisible: false
        });
    };
    /**
     * 导入数据
     */
    uploadVersion = () => {
        this.setState({
            uploadVisible: true
        });
    };
    /**
     *
     * @param file  {Object} 出错的文件
     * @param fileList  {Array} 当前值
     */
    onError = (file, fileList) => {
        console.log('Exceed limit', file, fileList);
    };

    /**
     * 保存文件
     * @type {{}}
     */
    saveImages = (value, call) => {
        /**
         * 获取数据
         */
        const _this = this;
        let url = event.event.url + '/v1/loginPageImages/save';
        this.$http.post(url, value)
            .then(function (response) {
                call();
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };

    /**
     *
     * @param file  {Object} 文件
     * @param value {Array} 值
     */
    onSuccess = (file, value) => {
        const dataList = file.response.data;
        let fileId = dataList[0].fileId;
        let fileName = file.name;
        let fileSize = file.size;
        this.saveImages({
            fileId: fileId,
            fileName: fileName,
            fileSize: fileSize
        }, () => {
            this.setState({
                uploadVisible: false
            }, () => {
                setTimeout(() => {
                    this.getAllPageImages();
                }, 200)
            });
        })
    };


    // ----------------------- 导入 -----------------------------------------

    render() {
        const actionUrl = event.event.url + '/v1/file/upload';
        const {mockData} = this.state;
        return (
            <div>
                <div className='container-header'>
                    <p>登录首页图片管理</p>
                </div>
                <Container className='container-main'>
                    <div className='container-btnBox' style={{marginTop: '0'}}>
                        <div className={styles.buttons}>
                            <Button onClick={() => this.uploadVersion()}
                                    className='pipe-btn-add'>添加图片</Button>
                            <span className={styles.caseNumber}>
                                <Input onChange={this.searchCondition.bind(this)} placeholder={"图片名字"}
                                       className={`${styles.input} ${styles.shortInput}`}/>
                                <Button
                                    type="primary"
                                    className='pipe-btn-search'
                                    onClick={this.getAllPageImages}
                                >
                                查询
                                </Button>
                            </span>
                        </div>
                    </div>
                    <div className='container-table'>
                        <Table dataSource={mockData} primaryKey="id" className={styles.table} rowSelection={{
                            onChange: this.onChange,
                            getProps: (record, index) => {
                                return {
                                    children: ""
                                };
                            },
                            columnProps: () => {
                                return {
                                    lock: 'left',
                                    width: 90,
                                    align: 'center'
                                };
                            },
                            titleAddons: () => {
                                return;
                            },
                            titleProps: () => {
                                return {
                                    children: ''
                                };
                            }
                        }}>
                            <Table.Column align="center" title="缩略图" cell={
                            (value, index, record) => {
                                return(
                                    <img width={80} height={80} src={event.event.url  + "/v1/file/download/"+record.fileId} />
                                )
                            }
                        }/>
                            <Table.Column align="center" title="文件名称" dataIndex="fileName"/>
                            <Table.Column align="center" title="文件大小" dataIndex="fileSize"/>
                            <Table.Column align="center" title="创建时间" dataIndex="createTime"/>
                            <Table.Column align="center" title="操作" cell={
                                (value, index, record) => {
                                    return (
                                        <div>
                                            <Button type="normal" size="small" text className='pipe-btn-delete'
                                                    onClick={this.deletePageImages.bind(this, record)} warning>
                                                <a onClick={() => {
                                                }}>删除</a>
                                            </Button>
                                        </div>
                                    )
                                }
                            }/>
                        </Table>
                        <ZgDialog config={this.state.config} cancelCall={this.cancelCall} okCall={this.okCall}/>
                        {/*-------------------------- 导入数据 --------------------------*/}
                        <Dialog
                            className='pipe-dialog'
                            title="导入元数据"
                            footer={<Button warning type="primary" onClick={this.onImportCloseDialog}>取消上传</Button>}
                            visible={this.state.uploadVisible}
                            onCancel={this.onImportCloseDialog.bind(this, 'cancelClick')}
                            onClose={this.onImportCloseDialog}>
                            <div>
                                <Upload
                                    headers={
                                        {
                                            'Authorization': sessionStorage.getItem("Authorization")
                                        }
                                    }
                                    accept={"images/*"}
                                    action={actionUrl}
                                    limit={5}
                                    listType="text"
                                    onSuccess={this.onSuccess = this.onSuccess.bind(this)}
                                    onError={this.onError = this.onError.bind(this)}>
                                    <Button type="primary" style={{margin: '0 0 10px'}}>上传图片</Button>
                                </Upload>
                                <Card {...commonProps} contentHeight={400}>
                                    <div className="custom-content">
                                        {
                                            this.state.errorMsg.length > 0 ? this.state.errorMsg.map(o => {
                                                return (
                                                    <Message key={"error"} title={""} type={"error"} size={"medium"}>
                                                        {o}
                                                    </Message>
                                                )
                                            }) : () => {
                                                return (
                                                    <Message key={"success"} title={"导入成功"} type={"success"}
                                                             size={"medium"}>
                                                        导入成功
                                                    </Message>
                                                )
                                            }
                                        }
                                    </div>
                                </Card>
                            </div>
                        </Dialog>
                        {/*-------------------------- 导入数据 --------------------------*/}
                    </div>
                </Container>
            </div>
        )
            ;
    }
}

export default PagesList;
